package chat.frame;

// 引入必要的工具类
import cn.hutool.core.io.FileUtil; // 文件操作工具类
import cn.hutool.core.util.StrUtil; // 字符串处理工具类
import login.frame.LoginFrame; // 登录框
import login.frame.ParentFrame;
import login.panel.LoginPanel; // 登录面板
import javax.swing.*; // 用于创建用户界面组件
import javax.swing.border.Border;
import java.awt.*; // 提供图形界面布局的工具
import java.awt.event.ActionEvent; // 事件处理
import java.awt.event.ActionListener; // 事件监听器
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.nio.charset.Charset; // 字符编码工具

public class ChatInterface extends ParentFrame {
    // 现代化配色方案
    private static final Color BACKGROUND_COLOR = new Color(252, 248, 253);
    private static final Color SURFACE_COLOR = new Color(255, 255, 255);
    private static final Color PRIMARY_COLOR = new Color(103, 80, 164);
    private static final Color ON_SURFACE_COLOR = new Color(28, 27, 31);
    private static final Color ON_SURFACE_VARIANT_COLOR = new Color(73, 69, 79);
    private static final Color OUTLINE_COLOR = new Color(201, 196, 206);
    private static final Color ERROR_COLOR = new Color(244, 67, 54);
    
    // 现代化字体
    private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 20);
    private static final Font BODY_FONT = new Font("微软雅黑", Font.PLAIN, 14);
    private static final Font LARGE_BODY_FONT = new Font("微软雅黑", Font.PLAIN, 16);
    
    // 间距常量
    private static final int SMALL_SPACING = 8;
    private static final int MEDIUM_SPACING = 16;
    private static final int LARGE_SPACING = 24;

    // 定义静态变量，用于保存文件路径
    public static String path = "src/";
    public static String path2 = "src/chat2.txt";

    // 定义用户界面组件
    private JTextArea chatArea;
    private JTextField inputField;
    private JButton sendButton;
    private JButton zhongZhi;
    private JComboBox<String> comboBox;
    private static volatile boolean zz = false;
    private JScrollPane chatScrollPane;

    // 构造函数，初始化聊天界面
    public ChatInterface() {
        super("天气预报AI助手 - Weather Forecast AI");
        createModernUI();
    }

    @Override
    protected int acWidth() {
        return 900; // 更宽的界面以适配现代设计
    }

    @Override
    protected int acHeight() {
        return 700; // 更高的界面
    }

    // 创建现代化用户界面
    private void createModernUI() {
        // 设置主容器
        Container container = getContentPane();
        container.setBackground(BACKGROUND_COLOR);
        container.setLayout(new BorderLayout());

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBackground(BACKGROUND_COLOR);
        mainPanel.setBorder(BorderFactory.createEmptyBorder(LARGE_SPACING, LARGE_SPACING, LARGE_SPACING, LARGE_SPACING));

        // 创建标题栏
        JPanel titlePanel = createTitlePanel();
        mainPanel.add(titlePanel, BorderLayout.NORTH);

        // 创建聊天区域
        JPanel chatPanel = createChatPanel();
        mainPanel.add(chatPanel, BorderLayout.CENTER);

        // 创建输入区域
        JPanel inputPanel = createInputPanel();
        mainPanel.add(inputPanel, BorderLayout.SOUTH);

        container.add(mainPanel, BorderLayout.CENTER);

        // 创建现代化菜单栏
        createModernMenuBar();
        
        // 设置窗口关闭操作为隐藏，而不是退出程序
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    }

    private JPanel createTitlePanel() {
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setBackground(BACKGROUND_COLOR);
        titlePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, LARGE_SPACING, 0));

        // 应用标题
        JLabel titleLabel = new JLabel("AI智能助手");
        titleLabel.setFont(TITLE_FONT);
        titleLabel.setForeground(ON_SURFACE_COLOR);
        titleLabel.setHorizontalAlignment(SwingConstants.LEFT);

        // 模型选择区域
        JPanel modelPanel = createModelSelectionPanel();

        titlePanel.add(titleLabel, BorderLayout.WEST);
        titlePanel.add(modelPanel, BorderLayout.EAST);

        return titlePanel;
    }

    private JPanel createModelSelectionPanel() {
        JPanel modelPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        modelPanel.setBackground(BACKGROUND_COLOR);

        JLabel modelLabel = new JLabel("模型:");
        modelLabel.setFont(BODY_FONT);
        modelLabel.setForeground(ON_SURFACE_VARIANT_COLOR);
        modelLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, SMALL_SPACING));

        String[] items = {"Weather Forecast Model", "deepseek", "阿里通义千问"};
        comboBox = new JComboBox<>(items);
        comboBox.setFont(BODY_FONT);
        comboBox.setPreferredSize(new Dimension(200, 35));
        comboBox.setBackground(SURFACE_COLOR);
        comboBox.setForeground(ON_SURFACE_COLOR);

        modelPanel.add(modelLabel);
        modelPanel.add(comboBox);

        return modelPanel;
    }

    private JPanel createChatPanel() {
        JPanel chatPanel = createModernCard("聊天记录");
        chatPanel.setLayout(new BorderLayout());
        chatPanel.setPreferredSize(new Dimension(0, 400));

        // 创建聊天区域
        chatArea = new JTextArea();
        chatArea.setLineWrap(true);
        chatArea.setWrapStyleWord(true);
        chatArea.setEditable(false);
        chatArea.setFont(LARGE_BODY_FONT);
        chatArea.setBackground(SURFACE_COLOR);
        chatArea.setForeground(ON_SURFACE_COLOR);
        chatArea.setBorder(BorderFactory.createEmptyBorder(
            MEDIUM_SPACING,
            MEDIUM_SPACING,
            MEDIUM_SPACING,
            MEDIUM_SPACING
        ));

        // 创建滚动面板
        chatScrollPane = new JScrollPane(chatArea);
        chatScrollPane.setBackground(SURFACE_COLOR);
        chatScrollPane.setBorder(BorderFactory.createEmptyBorder());
        chatScrollPane.getViewport().setBackground(SURFACE_COLOR);
        chatScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        chatScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

        chatPanel.add(chatScrollPane, BorderLayout.CENTER);

        return chatPanel;
    }

    private JPanel createInputPanel() {
        JPanel inputPanel = new JPanel(new BorderLayout());
        inputPanel.setBackground(BACKGROUND_COLOR);
        inputPanel.setBorder(BorderFactory.createEmptyBorder(LARGE_SPACING, 0, 0, 0));

        // 创建输入区域容器
        JPanel inputContainer = createModernCard("消息输入");
        inputContainer.setLayout(new BorderLayout());
        inputContainer.setPreferredSize(new Dimension(0, 80));

        // 创建输入框
        inputField = new JTextField("请输入您的问题...");
        inputField.setFont(LARGE_BODY_FONT);
        inputField.setPreferredSize(new Dimension(0, 45));
        inputField.setBackground(SURFACE_COLOR);
        inputField.setForeground(ON_SURFACE_COLOR);
        inputField.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(OUTLINE_COLOR, 1),
            BorderFactory.createEmptyBorder(SMALL_SPACING, MEDIUM_SPACING, SMALL_SPACING, MEDIUM_SPACING)
        ));
        
        // 占位符效果
        inputField.setForeground(ON_SURFACE_VARIANT_COLOR);
        inputField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                if (inputField.getText().equals("请输入您的问题...")) {
                    inputField.setText("");
                    inputField.setForeground(ON_SURFACE_COLOR);
                }
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                if (inputField.getText().trim().isEmpty()) {
                    inputField.setText("请输入您的问题...");
                    inputField.setForeground(ON_SURFACE_VARIANT_COLOR);
                }
            }
        });
        
        // 添加回车发送功能
        inputField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    sendMessage();
                }
            }
        });

        // 创建按钮面板
        JPanel buttonPanel = createButtonPanel();

        inputContainer.add(inputField, BorderLayout.CENTER);
        inputContainer.add(buttonPanel, BorderLayout.EAST);

        inputPanel.add(inputContainer, BorderLayout.CENTER);

        return inputPanel;
    }

    private JPanel createButtonPanel() {
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, SMALL_SPACING, 0));
        buttonPanel.setOpaque(false);

        // 中止按钮
        zhongZhi = createModernButton("中止", ERROR_COLOR, false);
        zhongZhi.setPreferredSize(new Dimension(80, 40));
        zhongZhi.addActionListener(e -> ChatInterface.zz = true);

        // 发送按钮
        sendButton = createModernButton("发送", PRIMARY_COLOR, true);
        sendButton.setPreferredSize(new Dimension(80, 40));
        sendButton.addActionListener(e -> sendMessage());

        buttonPanel.add(zhongZhi);
        buttonPanel.add(sendButton);

        return buttonPanel;
    }

    private JButton createModernButton(String text, Color color, boolean filled) {
        JButton button = new JButton(text);
        button.setFont(BODY_FONT);
        button.setFocusPainted(false);
        button.setBorderPainted(true);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        if (filled) {
            button.setBackground(color);
            button.setForeground(Color.WHITE);
            button.setBorder(BorderFactory.createEmptyBorder(SMALL_SPACING, MEDIUM_SPACING, SMALL_SPACING, MEDIUM_SPACING));
        } else {
            button.setBackground(SURFACE_COLOR);
            button.setForeground(color);
            button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(color, 1),
                BorderFactory.createEmptyBorder(SMALL_SPACING, MEDIUM_SPACING, SMALL_SPACING, MEDIUM_SPACING)
            ));
        }
        
        // 悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                if (filled) {
                    button.setBackground(color.darker());
                } else {
                    button.setBackground(new Color(color.getRed(), color.getGreen(), color.getBlue(), 20));
                }
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                if (filled) {
                    button.setBackground(color);
                } else {
                    button.setBackground(SURFACE_COLOR);
                }
            }
        });
        
        return button;
    }

    private JPanel createModernCard(String title) {
        JPanel card = new JPanel();
        card.setBackground(SURFACE_COLOR);
        card.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(OUTLINE_COLOR, 1),
            BorderFactory.createEmptyBorder(MEDIUM_SPACING, MEDIUM_SPACING, MEDIUM_SPACING, MEDIUM_SPACING)
        ));
        return card;
    }

    private void createModernMenuBar() {
        JMenuBar menuBar = new JMenuBar();
        menuBar.setBackground(SURFACE_COLOR);
        menuBar.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, OUTLINE_COLOR));

        JMenu menu = new JMenu("菜单");
        menu.setFont(BODY_FONT);
        menu.setForeground(ON_SURFACE_COLOR);

        JMenuItem exitItem = new JMenuItem("返回主界面");
        exitItem.setFont(BODY_FONT);
        exitItem.addActionListener(e -> {
            this.setVisible(false);
            LoginFrame.instance.setVisible(true);
        });

        JMenuItem clearItem = new JMenuItem("清空聊天记录");
        clearItem.setFont(BODY_FONT);
        clearItem.addActionListener(e -> {
            chatArea.setText("");
        });

        menu.add(clearItem);
        menu.addSeparator();
        menu.add(exitItem);
        menuBar.add(menu);

        setJMenuBar(menuBar);
    }

    private String extractCityName(String text) {
        // 简单的中文城市名识别逻辑
        if (text.contains("北京")) return "北京";
        if (text.contains("上海")) return "上海";
        if (text.contains("广州")) return "广州";
        if (text.contains("深圳")) return "深圳";
        if (text.contains("杭州")) return "杭州";
        if (text.contains("南京")) return "南京";
        if (text.contains("成都")) return "成都";
        if (text.contains("武汉")) return "武汉";
        if (text.contains("西安")) return "西安";
        if (text.contains("重庆")) return "重庆";
        return "";
    }

    // 发送消息的方法
    private void sendMessage() {
        String message = inputField.getText().trim();
        if (message.isEmpty() || message.equals("请输入您的问题...")) {
            return;
        }

        // 确定聊天记录的保存路径
        String p = path;
        String fileName = "chat{}.txt";
        fileName = StrUtil.format(fileName, LoginPanel.userId);
        p += fileName;
        final String pp = p;

        // 获取用户选择的模型
        String selectedModel = (String) comboBox.getSelectedItem();

        // 显示用户消息
        String userMessage = "Me: " + message + "\n";
        appendToChatArea(userMessage);
        inputField.setText("请输入您的问题...");
        inputField.setForeground(ON_SURFACE_VARIANT_COLOR);

        // 保存用户消息到文件
        FileUtil.appendString(userMessage, pp, Charset.defaultCharset());

        // 检查是否是天气查询
        String city = extractCityName(message);
        if (!city.isEmpty()) {
            new Thread(() -> {
                try {
                    String weatherInfo = BaiDuAI.getWeatherByCity(city);
                    String botResponse = "机器人: " + weatherInfo + "\n";
                    SwingUtilities.invokeLater(() -> appendToChatArea(botResponse));
                    FileUtil.appendString(botResponse, pp, Charset.defaultCharset());
                } catch (Exception e) {
                    String errorResponse = "机器人: 抱歉，获取天气信息时出现错误。\n";
                    SwingUtilities.invokeLater(() -> appendToChatArea(errorResponse));
                    FileUtil.appendString(errorResponse, pp, Charset.defaultCharset());
                }
            }).start();
            return;
        }

        // 处理其他模型回复
        new Thread(() -> {
            try {
                String response = "";
                if (StrUtil.equals(selectedModel, "阿里通义千问")) {
                    response = ALi.query(message);
                } else {
                    response = BaiDuAI.query(message);
                }

                if (!response.trim().isEmpty()) {
                    String botResponse = "机器人: ";
                    SwingUtilities.invokeLater(() -> appendToChatArea(botResponse));
                    
                    // 逐字输出效果
                    for (int i = 0; i < response.length(); i++) {
                        if (ChatInterface.zz) {
                            ChatInterface.zz = false;
                            SwingUtilities.invokeLater(() -> appendToChatArea("\n"));
                            return;
                        }
                        
                        final String character = String.valueOf(response.charAt(i));
                        SwingUtilities.invokeLater(() -> appendToChatArea(character));
                        
                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            break;
                        }
                    }
                    
                    SwingUtilities.invokeLater(() -> appendToChatArea("\n"));
                    FileUtil.appendString("机器人: " + response + "\n", pp, Charset.defaultCharset());
                }
            } catch (Exception e) {
                String errorResponse = "机器人: 抱歉，处理您的请求时出现错误。\n";
                SwingUtilities.invokeLater(() -> appendToChatArea(errorResponse));
                FileUtil.appendString(errorResponse, pp, Charset.defaultCharset());
            }
        }).start();
    }

    private void appendToChatArea(String text) {
        chatArea.append(text);
        chatArea.setCaretPosition(chatArea.getDocument().getLength());
        
        // 自动滚动到底部
        SwingUtilities.invokeLater(() -> {
            JScrollBar vertical = chatScrollPane.getVerticalScrollBar();
            vertical.setValue(vertical.getMaximum());
        });
    }

    // 程序入口
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            new ChatInterface().setVisible(true);
        });
    }
} 